package com.scedu.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller
public class RouterController {
    @RequestMapping({"/","/index"})
    public ModelAndView index(Map<String,Object> map){
        map.put("uname", getUname());
        return new ModelAndView("index", map);

    }

    @RequestMapping({"/about"})
    @PreAuthorize("isAnonymous()")
    public  String about(){

        return "/about";
    }

    @RequestMapping("/toLogin")
    public  String toLogin(){
        return "/login";
    }

    @PreAuthorize("hasAnyAuthority('p1','p2')")
    @RequestMapping("/level1/{id}")
    public  String level1(@PathVariable("id") String id)
    {
        return "level1/"+id;
    }

    @RequestMapping("/level2/{id}")
    public  String level2(@PathVariable("id") String id){
        return "level2/"+id;
    }
    @RequestMapping("/level3/{id}")
    public  String level3(@PathVariable("id") String id){
        return "level3/"+id;
    }
    //获取当前用户信息
    private String getUname(){
        String uname=null;
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        //用户身份
        Object principal=authentication.getPrincipal();
        if (principal==null){
            uname="匿名用户";
        }else {
            if (principal instanceof UserDetails){
                UserDetails userDetails=(UserDetails) principal;
                uname=userDetails.getUsername();
            }else{
                uname=principal.toString();
            }

        }
        return uname;

    }
}
